package io.gitee.terralian.code.generator.controller;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import io.gitee.terralian.code.generator.conf.StaticGlobalConf;
import io.gitee.terralian.code.generator.controller.request.PreviewCallRequest;
import io.gitee.terralian.code.generator.controller.request.PreviewGenerateRequest;
import io.gitee.terralian.code.generator.controller.request.PreviewOpenFolderRequest;
import io.gitee.terralian.code.generator.framework.entity.Result;
import io.gitee.terralian.code.generator.service.preview.GenerateService;
import io.gitee.terralian.code.generator.service.preview.PreviewService;
import io.gitee.terralian.code.generator.service.preview.entity.Preview;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("preview")
@AllArgsConstructor
public class PreviewController {

    private final PreviewService previewService;
    private final GenerateService generateService;

    @PostMapping("call")
    public Result<Preview> call(@RequestBody PreviewCallRequest request) {
        Preview preview = previewService.call(request);
        return Result.success(preview);
    }

    @PostMapping("params")
    public Result<Map<String, String>> getParams(@RequestBody(required = false) List<String> templateIds) {
        return Result.success(StaticGlobalConf.params);
    }

    @PostMapping("openFolder")
    public Result<Object> openFolder(@RequestBody PreviewOpenFolderRequest request) {
        try {
            File file = new File(request.getUrl());
            if (!file.exists()) {
                return Result.failMsg("文件夹不存在");
            }
            if (!file.isDirectory()) {
                return Result.failMsg("路径不是一个文件夹");
            }
            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().open(file);
            } else if (SystemUtils.IS_OS_WINDOWS) {
                Runtime.getRuntime().exec(new String[]{"cmd", "/c", "start", request.getUrl()});
            } else {
                return Result.failMsg("暂不支持该系统类型打开文件夹");
            }
        } catch (IOException e) {
            return Result.failMsg(e.getMessage());
        }
        return Result.defaultSuccess();
    }

    @PostMapping("generate")
    public Result<Object> generate(@RequestBody PreviewGenerateRequest request) {
        generateService.generate(request);
        return Result.defaultSuccess();
    }
}
